#include "TestContactsModel.h"
#include <QFile>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>

#define TEST_DB_PATH "./testAddressbook.sqlite"

namespace Dekko {
namespace Contacts {

void TestContactsModel::before()
{
    QFile(TEST_DB_PATH).remove();
    m_contactsModel = new Dekko::Contacts::ContactsModel(NULL, TEST_DB_PATH);
    m_contactsModel->setDatabaseName("name");
}

void TestContactsModel::after()
{
    delete m_contactsModel;
}

void TestContactsModel::testNewContact() {
    before();
    m_contactsModel->newContact("firstName", "lastName", "origanization",
                                QVariantList() << QVariant("email@email.com"));
    QSqlQuery query("SELECT COUNT(*) FROM contact", m_contactsModel->m_db);
    query.exec();
    query.next();
    qDebug() << query.record().value(0);
    QVERIFY(query.record().value(0).toInt() == 1);
    QVERIFY(m_contactsModel->rowCount() == 1);
    after();
}

void TestContactsModel::testRemoveStaleContactMoreThan()
{
    before();
    QDateTime dateTime = QDateTime::currentDateTime();
    QList<QString> remainingContactIds;
    for (int i = 0; i < 2; i++) {
        QString contactId = m_contactsModel->newContact("firstName", "lastName", "origanization",
                                                             QVariantList() << QVariant("email@email.com"));
        m_contactsModel->setLastContactTime(contactId, dateTime);
        remainingContactIds << contactId;
        dateTime = dateTime.addDays(-1);
    }
    for (int i = 0; i < 2; i++) {
        QString contactId = m_contactsModel->newContact("firstName", "lastName", "origanization",
                                                             QVariantList() << QVariant("email@email.com"));
        m_contactsModel->setLastContactTime(contactId, dateTime);
        dateTime = dateTime.addDays(-1);
    }
    m_contactsModel->removeStaleContactMoreThan(2);
    QVERIFY(m_contactsModel->rowCount() == 2);
    QVERIFY(remainingContactIds.contains(
                m_contactsModel->data(
                    m_contactsModel->index(0), ContactsModel::RoleContactId).toString()));
    QVERIFY(remainingContactIds.contains(
                m_contactsModel->data(
                    m_contactsModel->index(1), ContactsModel::RoleContactId).toString()));
    after();
}

}
}

QTEST_MAIN(Dekko::Contacts::TestContactsModel)
